from flask import Flask, render_template, jsonify, request, send_file
import json
import os
from datetime import datetime, timedelta
import pandas as pd
from transformers import pipeline
import jieba
import jieba.analyse
from collections import Counter
import random

app = Flask(__name__)

# 初始化情感分析模型
sentiment_analyzer = pipeline(
    "sentiment-analysis",
    model="IDEA-CCNL/Erlangshen-Micro-2.6M",
    tokenizer="IDEA-CCNL/Erlangshen-Micro-2.6M"
)

# 模拟微博热搜数据
def get_hot_topics():
    """获取模拟的微博热搜数据"""
    topics = [
        {"rank": 1, "title": "双十一购物节", "heat": "爆", "url": "#"},
        {"rank": 2, "title": "新能源汽车销量创新高", "heat": "沸", "url": "#"},
        {"rank": 3, "title": "考研报名开始", "heat": "热", "url": "#"},
        {"rank": 4, "title": "冬季流感预防", "heat": "新", "url": "#"},
        {"rank": 5, "title": "AI技术发展", "heat": "热", "url": "#"},
        {"rank": 6, "title": "环保新政策", "heat": "新", "url": "#"},
        {"rank": 7, "title": "教育改革方案", "heat": "沸", "url": "#"},
        {"rank": 8, "title": "健康饮食趋势", "heat": "热", "url": "#"},
        {"rank": 9, "title": "远程办公模式", "heat": "新", "url": "#"},
        {"rank": 10, "title": "数字人民币试点", "heat": "热", "url": "#"}
    ]
    return topics

# 模拟评论数据
def generate_comments(topic, count=50):
    """生成模拟评论数据"""
    positive_comments = [
        "太棒了！支持这个话题",
        "说得很有道理，点赞",
        "这个政策真的很好，为民着想",
        "期待已久，终于来了",
        "非常有意义，支持！"
    ]
    
    neutral_comments = [
        "了解一下情况",
        "看看后续发展",
        "这个要看具体实施",
        "保持关注",
        "理性看待"
    ]
    
    negative_comments = [
        "不太看好这个",
        "感觉没什么用",
        "又要割韭菜了",
        "形式主义罢了",
        "不抱太大希望"
    ]
    
    comments = []
    for i in range(count):
        sentiment_type = random.choice(['positive', 'neutral', 'negative'])
        if sentiment_type == 'positive':
            text = random.choice(positive_comments)
        elif sentiment_type == 'neutral':
            text = random.choice(neutral_comments)
        else:
            text = random.choice(negative_comments)
            
        comments.append({
            'id': i + 1,
            'text': text,
            'user': f'用户{i+1}',
            'time': (datetime.now() - timedelta(hours=random.randint(1, 24))).strftime('%Y-%m-%d %H:%M'),
            'likes': random.randint(0, 100),
            'sentiment': sentiment_type
        })
    
    return comments

@app.route('/')
def index():
    """首页"""
    topics = get_hot_topics()
    return render_template('index.html', topics=topics)

@app.route('/api/topics')
def api_topics():
    """获取热搜话题API"""
    topics = get_hot_topics()
    return jsonify(topics)

@app.route('/api/analysis/<topic>')
def api_analysis(topic):
    """获取话题分析数据"""
    # 获取评论
    comments = generate_comments(topic, 100)
    
    # 情感分析
    sentiments = {'positive': 0, 'neutral': 0, 'negative': 0}
    for comment in comments:
        sentiments[comment['sentiment']] += 1
    
    # 关键词提取
    all_text = ' '.join([c['text'] for c in comments])
    keywords = jieba.analyse.extract_tags(all_text, topK=10, withWeight=True)
    keywords = [{'word': k[0], 'weight': k[1]} for k in keywords]
    
    # 时间分布
    time_dist = {}
    for comment in comments:
        hour = comment['time'].split(' ')[1].split(':')[0]
        time_dist[hour] = time_dist.get(hour, 0) + 1
    
    return jsonify({
        'topic': topic,
        'sentiments': sentiments,
        'keywords': keywords,
        'time_distribution': time_dist,
        'total_comments': len(comments)
    })

@app.route('/api/export/<topic>')
def api_export(topic):
    """导出分析结果"""
    comments = generate_comments(topic, 100)
    
    # 创建DataFrame
    df = pd.DataFrame(comments)
    
    # 保存为CSV
    filename = f'data/{topic}_analysis_{datetime.now().strftime("%Y%m%d_%H%M%S")}.csv'
    df.to_csv(filename, index=False, encoding='utf-8-sig')
    
    return send_file(filename, as_attachment=True)

if __name__ == '__main__':
    # 确保数据目录存在
    os.makedirs('data', exist_ok=True)
    app.run(debug=True, host='0.0.0.0', port=5000)
